import { RouteRecordRaw } from 'vue-router'
import router from '@/router'
import fs from 'fs'
import path from 'path'

interface SitemapUrl {
  loc: string
  lastmod: string
  changefreq: string
  priority: string
}

export class SitemapGenerator {
  private domain: string
  private urls: SitemapUrl[] = []

  constructor(domain: string = 'https://your-domain.com') {
    this.domain = domain
  }

  private generateUrlsFromRoutes(routes: RouteRecordRaw[]) {
    routes.forEach(route => {
      if (route.meta?.excludeFromSitemap) {
        return
      }

      this.urls.push({
        loc: `${this.domain}${route.path}`,
        lastmod: new Date().toISOString().split('T')[0],
        changefreq: 'weekly',
        priority: route.meta?.sitemapPriority || '0.8'
      })

      if (route.children) {
        this.generateUrlsFromRoutes(route.children)
      }
    })
  }

  private generateSitemapXml(): string {
    const xmlContent = [
      '<?xml version="1.0" encoding="UTF-8"?>',
      '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',
      ...this.urls.map(url => this.generateUrlXml(url)),
      '</urlset>'
    ].join('\n')

    return xmlContent
  }

  private generateUrlXml(url: SitemapUrl): string {
    return [
      '  <url>',
      `    <loc>${this.escapeXml(url.loc)}</loc>`,
      `    <lastmod>${url.lastmod}</lastmod>`,
      `    <changefreq>${url.changefreq}</changefreq>`,
      `    <priority>${url.priority}</priority>`,
      '  </url>'
    ].join('\n')
  }

  private escapeXml(unsafe: string): string {
    return unsafe.replace(/[<>&'"]/g, c => {
      switch (c) {
        case '<': return '&lt;'
        case '>': return '&gt;'
        case '&': return '&amp;'
        case '\'': return '&apos;'
        case '"': return '&quot;'
        default: return c
      }
    })
  }

  private generateRobotsTxt(): string {
    return `User-agent: *
Allow: /
Sitemap: ${this.domain}/sitemap.xml

# 百度爬虫
User-agent: Baiduspider
Allow: /

# 谷歌爬虫
User-agent: Googlebot
Allow: /`
  }

  public async generate() {
    this.generateUrlsFromRoutes(router.routes)

    const sitemapXml = this.generateSitemapXml()
    const sitemapPath = path.resolve(process.cwd(), 'dist/sitemap.xml')
    await fs.promises.writeFile(sitemapPath, sitemapXml, 'utf-8')

    const robotsTxt = this.generateRobotsTxt()
    const robotsPath = path.resolve(process.cwd(), 'dist/robots.txt')
    await fs.promises.writeFile(robotsPath, robotsTxt, 'utf-8')

    this.urls = []
  }
} 